import 'package:flutter/material.dart';
import 'package:demo_day_1/services/gitcode_service.dart';
import 'package:demo_day_1/page/home/home_page.dart'; // 登录成功后跳转到首页
///dFwmiRCDi86AJvXdvD3NfdFj
class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController _tokenController = TextEditingController();
  final GitcodeService _gitcodeService = GitcodeService();
  bool _isLoading = false;

  void _login() async {
    setState(() {
      _isLoading = true;
    });

    final token = _tokenController.text.trim();
    if (token.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入您的个人访问令牌')),
      );
      setState(() {
        _isLoading = false;
      });
      return;
    }

    try {
      bool success = await _gitcodeService.login(token);
      if (success) {
        // 登录成功，导航到主页
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => const HomeScreen()),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('登录失败，请检查您的令牌是否正确或过期')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('登录时发生错误: $e')),
      );
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Gitcode 登录'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: _tokenController,
                decoration: const InputDecoration(
                  labelText: '个人访问令牌',
                  border: OutlineInputBorder(),
                  hintText: '请输入您的 Gitcode Personal Access Token',
                ),
                obscureText: false, // 令牌是敏感信息，可以隐藏
              ),
              const SizedBox(height: 20),
              _isLoading
                  ? const CircularProgressIndicator()
                  : ElevatedButton(
                      onPressed: _login,
                      child: const Text('登录'),
                    ),
              const SizedBox(height: 20),
              TextButton(
                onPressed: () {
                  // TODO: 可以添加一个链接引导用户去 Gitcode 生成 token
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('请前往 Gitcode 网站生成个人访问令牌')),
                  );
                },
                child: const Text('如何获取个人访问令牌？'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
